package com.hooker.helper;

import android.os.Process;

import com.hooker.Dig;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lenovo
 * @date 2020/5/19
 * 请求统计的类
 */
public class RequestStatsManager {

    private static final Map<String, Request> stats = new HashMap<>();
    private volatile static RequestStatsManager INSTANCE;

    private static class SingleTonHolder {
        private static final RequestStatsManager INSTANCE = new RequestStatsManager();
    }

    public static RequestStatsManager getInstance() {
        return SingleTonHolder.INSTANCE;
    }

    private RequestStatsManager() {
    }


    /**
     * 添加一个请求拦截
     *
     * @param url
     * @return
     */
    public synchronized Integer addRequestStats(String host, String processName) {
        String url = host;
        Request request = stats.get(url);
        if (request == null) {
            request = new Request();
            stats.put(url, request);
            Request request2 = stats.get(url);
        } else {
            request.number.getAndIncrement();
        }
        return request.number.get();
    }

    /**
     * 获取一个请求数
     *
     * @param url
     * @return
     */
    public Integer getRequestStats(String url) {
        synchronized (stats) {
            Request request = stats.get(url);
            return request == null ? 0 : request.number.get();
        }
    }

    private static class Request {
        private AtomicInteger number;

        public Request() {
            number = new AtomicInteger(1);
        }
    }

}
